<?php
namespace Modules\Order\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Order\Http\Resources\OrderDetailResource;
use Modules\Auth\Http\Resources\UserResource;
use Modules\Good\Http\Resources\GoodResource;

class OrderResource extends JsonResource{
    public function toArray($request): array{
        return [
            'id'=>$this->id,
            'order_id'=>$this->order_id,
            'user_id'=>$this->user_id,
            'amount'=>$this->amount,
            'status'=>$this->status,
            'address'=>$this->address,
            'express_type'=>$this->express_type,
            'express_no'=>$this->express_no,
            'pay_time'=>$this->pay_time,
            'pay_type'=>$this->pay_type,
            'trade_no'=>$this->trade_no,
            // 'created'=>$this->created_at->format('Y-m-d H:i:s'),
            // 'updated'=>$this->updated_at->format('Y-m-d H:i:s'),
            'user'=>$this->includeUser(),
            'orderDetails'=>$this->includeDetails(),
            'goods'=>$this->includeGoods(),
        ];
    }
    public function includeUser(){
        return $this->whenLoaded('user',function($user){
            return new UserResource($user);
        });
    }
    public function includeDetails(){
        return $this->whenLoaded('orderDetail',function($orderDetails){
            return OrderDetailResource::collection($orderDetails);
        });
    }
    public function includeGoods(){
        return $this->whenLoaded('orderDetail',function($orderDetails){
            return GoodResource::collection($orderDetails->map(function($orderDetail){
                return $orderDetail->goods;
            }));
        });
    }
}
